#import <Foundation/Foundation.h>
#import <objc/runtime.h>
#import <UIKit/UIKit.h>
#import <UIKit/UIApplication.h>
#import <Preferences/PSSpecifier.h>
#import <LockInfo/Plugin.h>

#import "framework/FWCommon.h"
#import "framework/FWApplication.h"

#import "PICommon.h"
#import "PITaskIntegration.h"
#import "PIContext.h"
#import "PIPlugin.h"

#import "PIContextListPrefs.h"


@implementation PIContextListPrefs

@synthesize contexts;


// ******************************************************************************************
#pragma mark -
#pragma mark Initialisation and object management

- (id)initForContentSize:(CGSize)contentSize
{
    self.contexts = nil;
    
    if ([super respondsToSelector:@selector(initForContentSize:)])
        self = [super initForContentSize:contentSize];
    else
        self = [super init];
    
    return self;
}

- (void)dealloc
{
    [contexts release];
    
    [super dealloc];
}


// ******************************************************************************************
#pragma mark -
#pragma mark Get list of contexts

- (void)intitialiseData
{
    if (!self.contexts) {
        UIPasteboard* pasteBoard = [UIPasteboard pasteboardWithName:kPIStatusPasteboard create:NO];
        NSString* dbPath = FWStringValueFromPasteboard(pasteBoard, kPIPasteboardDBPath);
        NSNumber* dbVersion = FWNumberValueFromPasteboard(pasteBoard, kPIPasteboardDBVersion);
        
        if (dbPath && dbVersion) {
            FWApplication* app = [[FWApplication alloc] init];
            app.databasePath = dbPath;
            app.fwPlugin = [[[PIPlugin alloc] initWithPIVersion:dbVersion.integerValue] autorelease];
            
            self.contexts = [PITaskIntegration arrayOfContexts:app earliest:nil counts:NO];
            [app release];
        }
    }
}

- (NSArray*)contextValues:(id)target
{
    [self intitialiseData];

    NSMutableArray* values = [NSMutableArray arrayWithCapacity:contexts.count + 1];
    [values addObject:[NSNumber numberWithInt:-1]];
    
    for (PIContext* context in contexts)
        [values addObject:[NSNumber numberWithInt:context.key]];
    
    return values;
}

- (NSArray*)contextTitles:(id)target
{
    [self intitialiseData];
    
    NSMutableArray* titles = [NSMutableArray arrayWithCapacity:contexts.count + 1];
    [titles addObject:localize([NSBundle bundleForClass:[self class]], @"Context/None")];

    for (PIContext* context in contexts)
        [titles addObject:context.title];

    return titles;
}

@end
